#include "sled_scene_manager/sled_scene_manager_class/sled_scene_manager_class.h"
#include <string.h>

#include "debug.h"
#define LOG_TAG "[SLED_SCENE_MANAGER_CLASS]"
inline static sled_scene_t* search_scene_by_name(sled_scene_t* scene_array, const char *name)
{
    while(scene_array != NULL)
    {
        if(scene_array->scene_name != NULL)
        {
            if(strcmp(scene_array->scene_name, name) == 0)
            {
                return scene_array;
            }
            else
            {
                scene_array ++;
            }
        }
        if(scene_array->scene_name == NULL)
        {
            break;
        }
    }
    return NULL;
}

void sled_scene_conductor(sled_scene_manager_class_t *this)
{
    uint32_t time;
    time = sled_scene_handler(this->curScene);
    if(this->timeout_handle != 0)
    {
        sys_timeout_del(this->timeout_handle);
        this->timeout_handle = 0;
    }
    if(time != 0)
    {
        this->timeout_handle = sys_timeout_add(this, sled_scene_conductor,time);
    }
}

#define SLED_MANAGER_ERR_OK 0
#define SLED_MANAGER_ERR_NO_SUCH_SCENE -1
__weak int sled_scene_manager_selectScene(sled_scene_manager_class_t*this ,const char *sceneName)
{  
    sled_scene_t* scene;
    scene = search_scene_by_name(this->scene_array, sceneName);
    if(scene == NULL)
    {
        log_info("No sled scene matched\n");
        return SLED_MANAGER_ERR_NO_SUCH_SCENE;
    }
    else
    {
        log_info("sled conduct:%s\n",scene->scene_name);
        this->spin_lock();
        // if(scene != this->curScene)
        // {
        //     if(this->timeout_handle != 0)
        //     {
        //         logln_pos("del timeout:%d",this->timeout_handle);
        //         usr_timeout_del(this->timeout_handle);
        //         this->timeout_handle = 0;
        //     }
        // }
        this->curScene = scene;
        this->curScene->cur_action_index = 0;
        sled_scene_conductor(this);
        // sled_scene_conductor(this->curScene); 20240814:传参指针类型错误,编译器未报语法错误
        this->spin_unlock();
    }
    return 0;
}

__weak const char* sled_scene_manager_getCurScene(sled_scene_manager_class_t*this)
{
    return this->curScene->scene_name;
}